<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<cl-filter label="状态">
				<cl-select :options="statusList" prop="status" style="width: 120px" />
			</cl-filter>
			<cl-filter label="应用">
				<cl-select :options="appList" prop="appId" style="width: 120px" />
			</cl-filter>
			<cl-flex1 />
			<!-- 关键字搜索 -->
			<cl-search-key field="name" :field-list="[
				{
					label: '任务名称',
					value: 'name'
				},
				{
					label: '应用名称',
					value: 'appName'
				},
				{
					label: 'Topic',
					value: 'topic'
				}
			]" />
		</cl-row>
		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table">
				<template #slot-removes="{ scope }">
					<el-button text bg @click="onRemove(scope.row)">移除</el-button>
				</template>
				<template #slot-starts="{ scope }">
					<el-button text bg v-if="scope.row.status == 3" type="primary"
						@click="onStart(scope.row)">启动</el-button>
				</template>
				<template #slot-stops="{ scope }">
					<el-button text bg v-if="scope.row.status == 0 || scope.row.status == 1" type="primary"
						@click="onStop(scope.row)">停止</el-button>
				</template>
				<template #slot-record="{ scope }">
					<el-button text bg type="primary" @click="linkRecord(scope.row)">记录</el-button>
				</template>
			</cl-table>
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
	</cl-crud>
</template>

<script lang="ts" name="task-job" setup>
import { useCrud, useTable, useUpsert } from "@cool-vue/crud";
import { router, useCool } from "/@/cool";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref } from "vue";

const { service } = useCool();
//状态
const statusList = ref([
	{ label: "待执行", value: 0 },
	{ label: "执行中", value: 1, color: "#67C23A" },
	{ label: "已完成", value: 2, color: "#67c23a" },
	{ label: "已停止", value: 3, color: "#909399" }
]);

const appList = ref([]);

onMounted(() => {
	//应用名称下拉项
	service.task.app.list().then((res) => {
		appList.value = res.map((item) => {
			return { ...item, label: item.name, value: item.id };
		});
	});
});

// cl-upsert
const Upsert = useUpsert({
	props: {
		labelWidth: "80px"
	},
	onOpened(data) {
		console.log("data:", data);
		//应用名称下拉项
		service.task.app.list().then((res) => {
			const result: any = res.map((item) => {
				return { ...item, label: item.name, value: item.id };
			});
			Upsert.value?.setOptions("appId", result);
		});
		//Topic下拉项
		service.task.topic.list().then((res) => {
			const result: any = res.map((item) => {
				return { ...item, label: item.name, value: item.name };
			});
			Upsert.value?.setOptions("topic", result);
		});
		data.body = data.body ? JSON.stringify(data.body) : null;
		//如果type==0，隐藏delay，如果type==1，隐藏cron和every
		if (!data || data.type == 0) {
			Upsert.value?.hideItem("delay");
		} else {
			Upsert.value?.hideItem("cron");
			Upsert.value?.hideItem("every");
		}
	},
	items: [
		{
			prop: "appId",
			label: "应用",
			required: true,
			component: { name: "el-select" }
		},
		{ prop: "jobId", label: "任务ID", required: true, component: { name: "el-input" } },
		{ prop: "topic", label: "Topic", required: true, component: { name: "el-select" } },
		{ prop: "name", label: "名称", required: true, component: { name: "el-input" } },
		{
			prop: "type",
			label: "类型",
			component: {
				name: "el-radio-group",
				options: [
					{ label: "重复", value: 0 },
					{ label: "延时", value: 1, color: "#67C23A" }
				],
				props: {
					onChange: (val: number) => {
						if (val == 0) {
							Upsert.value?.hideItem("delay");
							Upsert.value?.showItem("cron");
							Upsert.value?.showItem("every");
							Upsert.value?.setForm("delay", "");
						} else {
							Upsert.value?.hideItem("cron");
							Upsert.value?.hideItem("every");
							Upsert.value?.showItem("delay");
							Upsert.value?.setForm("cron", "");
							Upsert.value?.setForm("every", "");
						}
					}
				}
			},
			value: 0,
			required: true,
			span: 24
		},
		{ prop: "cron", label: "cron", component: { name: "el-input" }, span: 12 },
		{
			prop: "every",
			label: "时间间隔",
			component: {
				name: "el-input",
				props: { placeholder: "请输入时间间隔，单位：毫秒" }
			},
			span: 12
		},
		{
			prop: "delay",
			label: "延时时间",
			component: { name: "el-input", props: { placeholder: "请输入延时时间，单位：毫秒" } }
		},
		{
			prop: "startTime",
			label: "开始时间",
			component: {
				name: "el-date-picker",
				props: { type: "datetime", valueFormat: "YYYY-MM-DD HH:mm:ss" }
			}
		},
		{
			prop: "remark",
			label: "备注",
			component: { name: "el-input", props: { type: "textarea", rows: 5 } }
		},
		{
			prop: "body",
			label: "业务参数",
			component: {
				name: "el-input",
				props: { type: "textarea", rows: 8, placeholder: "请输入业务参数，必须为JSON格式" }
			}
		}
	],
	async onSubmit(data, { done, close, next }) {
		if (data.type == 0) {
			//cron和every必须有一个有值
			if (!data.cron && !data.every) {
				ElMessage.warning("cron和every必须有一个有值");
				done();
				return;
			}
		}
		const newData = await next({
			...data
		});
		console.log("newData:", newData);
		done();
		close();

		// done 关闭加载状态
		// close 关闭弹窗
	}
});

// cl-table
const Table = useTable({
	columns: [
		{ prop: "jobId", label: "任务ID", minWidth: 120 },
		{ prop: "name", label: "任务名称", minWidth: 140 },
		{ prop: "appName", label: "应用名称", minWidth: 140 },
		{ prop: "topic", label: "Topic", minWidth: 140 },
		{
			prop: "type",
			label: "类型",
			dict: [
				{ label: "重复", value: 0 },
				{ label: "延时", value: 1, color: "#67C23A" }
			],
			minWidth: 120
		},
		{
			prop: "status",
			label: "状态",
			dict: statusList.value,
			minWidth: 120
		},
		{ prop: "cron", label: "cron", minWidth: 120 },
		{ prop: "every", label: "时间间隔", minWidth: 120 },
		{ prop: "delay", label: "延时时间", minWidth: 120 },
		{ prop: "nextRunTime", label: "下次执行时间", minWidth: 120 },
		{ prop: "startTime", label: "开始时间", minWidth: 160 },
		{ prop: "remark", label: "备注", showOverflowTooltip: true, minWidth: 120 },
		// { prop: "body", label: "业务参数", showOverflowTooltip: true, minWidth: 120 },
		{ prop: "createTime", label: "创建时间", sortable: "desc", width: 160 },
		{ prop: "updateTime", label: "更新时间", sortable: "custom", width: 160 },
		{
			type: "op",
			buttons: ["edit", "slot-removes", "slot-starts", "slot-stops", "slot-record"],
			width: 320
		}
	]
});

const onRemove = async (row: any) => {
	ElMessageBox.confirm(`确定要移除？`, "提示", {
		type: "warning"
	}).then(() => {
		//调用移除方法
		service.task.job.remove({ id: row.id }).then(() => {
			ElMessage.success("移除成功");
			Crud.value?.refresh();
		});
	});
};

//启动
const onStart = (row: any) => {
	//调用启动方法
	service.task.job.start({ id: row.id }).then(() => {
		ElMessage.success("已停止");
		Crud.value?.refresh();
	});
};
//停止
const onStop = (row: any) => {
	ElMessageBox.confirm(`确定要停止？`, "提示", {
		type: "warning"
	}).then(() => {
		//调用停止方法
		service.task.job.stop({ id: row.id }).then(() => {
			ElMessage.success("已停止");
			Crud.value?.refresh();
		});
	});
};
//查看记录
const linkRecord = (row: any) => {
	console.log("row:", row);
	router.push({
		path: "/task/record",
		query: {
			id: row.id
		}
	});
};

// cl-crud
const Crud = useCrud(
	{
		service: service.task.job
	},
	(app) => {
		app.refresh();
	}
);
</script>
